<template>
  <div>
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <span>{{ userInfo.managerName }}</span>
        </div>
      </template>
      <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeUpload"
        style="border-radius: 50%;">

        <img v-if="imgUrl" style="border-radius: 50%;" :src="imgUrl" class="avatar">
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>

        <!-- <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 500kb
          </div>
        </template> -->
      </el-upload>
      <div>电话号码：{{ userInfo.managerPhone }}</div>
      <template #footer><el-button @click="editDialog = true">修改信息</el-button></template>

    </el-card>

    <el-dialog v-model="editDialog" title="修改信息" width="400">

      <el-form :model="dialogForm" ref="dialogRef" label-width="70px">
        <el-form-item label="用户名" prop="managerName">
          <el-input v-model="dialogForm.managerName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialog = false">Cancel</el-button>
        <el-button type="primary" @click="submit">
          Confirm
        </el-button>
      </div>
    </template>
    </el-dialog>
    <!-- Conditional display for upload component -->



  </div>
  <el-dialog v-model="dialogVisible" title="编辑图片" width="800">
    <div v-if="imageSrc" style="display: flex; justify-content: space-between; align-items: center;">

      <!-- Display cropped image or original image if not cropped with background -->
      <div id="preview" class="preview">
        <img ref="previewImage" :src="croppedImageSrc || imageSrc" alt="Preview Image"
          style="max-width: 100%; height: 400px;" />
      </div>

      <!-- Upload image section without background -->
      <div style="width: 50%; padding: 10px; display: flex; justify-content: center; align-items: center;">
        <img ref="uploadImage" :src="imageSrc" alt="Source Image" style="max-width: 100%; height: 400px;" />
      </div>
    </div>

    <!-- Centered buttons -->
    <div v-if="imageSrc" style="margin-top: 20px; text-align: center;">
      <el-button @click="clearImage">重新选择</el-button>
      <el-button type="primary" @click="uploadAvatar">上传头像</el-button>
    </div>
  </el-dialog>


</template>

<script setup>
import { ref, nextTick, onBeforeUnmount, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
import axios from 'axios';

let userInfo = JSON.parse(localStorage.getItem("userInfo"))
let dialogForm = ref(Object.assign({},userInfo))
let editDialog = ref(false)

let uploadUrl = axios.defaults.baseURL + "upload?flag=7"
let imgUrl = ref(axios.defaults.baseURL + "image/user/avatar1744075628670.png")
const imageSrc = ref(null);
const croppedImageSrc = ref(null);
const dialogVisible = ref(false);
const fileList = ref([]);

const uploadImage = ref(null);
const previewImage = ref(null);
let cropper = null;
const attraction_detail = ref({ imageUrl: '' })
const beforeUpload = (file) => {
  dialogVisible.value = true

  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
    return false;
  }
  const reader = new FileReader();
  reader.onload = async (e) => {
    imageSrc.value = e.target.result
    await nextTick();
    initCropper();
  };
  reader.readAsDataURL(file);
  return false;
};

const initCropper = () => {
  if (cropper) {
    cropper.destroy();
  }
  if (!uploadImage.value) return;
  cropper = new Cropper(uploadImage.value, {
    aspectRatio: 1,//一比一裁剪区域
    preview: "#preview",
    viewMode: 1,
  });
};

const cropImage = () => {
  if (cropper) {
    const canvas = cropper.getCroppedCanvas({
      width: 200,
      height: 200,
    });
    croppedImageSrc.value = canvas.toDataURL('image/png');
  }
};

const clearImage = () => {
  imageSrc.value = null;
  croppedImageSrc.value = null;
  fileList.value = [];
  if (cropper) {
    cropper.destroy();
    cropper = null;
  }
};


const dataURLToBlob = (dataURL) => {
  const arr = dataURL.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};

async function getUserInfo() {
  let id = JSON.parse(localStorage.getItem("userInfo")).managerId;
  const { data: res } = await axios.get(
    "/manager/getManagerById",
    { params: { id: id } }
  );
  if (res.code != 200) {
  } else {
    imgUrl.value = res.data.avatar;
  }

}
async function uploadAvatar() {
  let id = JSON.parse(localStorage.getItem("userInfo")).managerId;

  cropImage()
  const blob = dataURLToBlob(croppedImageSrc.value);
  console.log('crop src......', croppedImageSrc.value)
  const formData = new FormData();
  formData.append('file', blob, 'avatar' + id + '.png' + "?t=" + Date.now()); // 注意这里的表单字段名应为'file'
  const { data: res } = await axios.post(
    "upload?flag=7", formData
  )
  if (res.code != 200) {
  } else {
    imgUrl.value = res.data.url;
    dialogVisible.value = false
    getUserInfo()
  }
}
async function submit(){
  editDialog.value = false
  const { data: res } = await axios.post(
    "/manager/updateInfo",
    dialogForm.value
  );
  if (res.code != 200) {
  } else {
getUserInfo() }
}

onBeforeUnmount(() => {
  if (cropper) {
    cropper.destroy();
  }
});
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.upload-demo {

  margin: 8px;
  border-radius: 50%;
}

.upload-demo .el-upload {
  display: block;
  width: 100%;
}

/deep/.el-upload--picture-card {
  margin: 8px;
  border-radius: 50%;
}


.el-upload__text {
  color: #606266;
  font-size: 14px;
  line-height: 22px;
  margin-top: 5px;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  margin-top: 7px;
}

.upload-demo {
  /* text-align: center; */
}

/* .avatar {
  width: 200px;
  height: 200px;
  margin: 50px;
  border-radius: 50%;
} */

.cropper-view-box,
.cropper-face {
  border-radius: 50%;
}

.preview {
  width: 180px;
  height: 180px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 auto
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);

}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>